package com.javaweb.upload;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;

import com.javaweb.dao.StudentDao;
import com.javaweb.model.Student;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/20 19:56
 */

@Slf4j
public class StudentUploadListener implements ReadListener<StudentUploadDto> {
    /**
     * 每次读取的最多行数
     */
    private static final int MAX_ROW_PER_READ = 5 ;
    /**
     * 利用studentDao将读取到的数据，批量存入数据库。
     */
    private StudentDao studentDao ;
    /**
     * 存储读取到的数据
     */
    private List<StudentUploadDto> cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;

    public StudentUploadListener(StudentDao studentDao) {
        this.studentDao = studentDao ;
    }
    /**
     * 每次easyexcel读取到一行数据，都会调用该方法
     * @param studentUploadDto
     * @param analysisContext
     */
    @Override
    public void invoke(StudentUploadDto studentUploadDto, AnalysisContext analysisContext) {
        log.info("读取到一条学生信息：{}", studentUploadDto) ;
        cachedReadData.add(studentUploadDto) ;
        if (cachedReadData.size() >= MAX_ROW_PER_READ) {

            // 达到每行最大读取数，需要将数据写入数据库
            log.info("数据写入数据库：{}", cachedReadData) ;
           // studentDao.insertBatch(convertToStudent(cachedReadData)) ;
            // 清空缓存数据
            cachedReadData = ListUtils.newArrayListWithExpectedSize(MAX_ROW_PER_READ) ;

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 所有数据读取完毕，需要将剩余的数据写入数据库
        log.info("数据写入数据库：{}", cachedReadData) ;
        //studentDao.insertBatch(convertToStudent(cachedReadData)) ;
        log.info("读取完毕");


    }

    private static List<Student> convertToStudent(List<StudentUploadDto> studentUploadDtoList) {
        return studentUploadDtoList.stream().map(studentUploadDto -> {
            Student student = new Student() ;
            student.setName(studentUploadDto.getName()) ;
            student.setAge(Integer.valueOf(studentUploadDto.getAge())) ;
            student.setGender(studentUploadDto.getGender()) ;
            student.setBirthday(studentUploadDto.getBirthday()) ;
            student.setPhone(studentUploadDto.getPhone()) ;
            student.setEmail(studentUploadDto.getEmail()) ;
            return student ;
        }).collect(Collectors.toList()) ;
    }
}
